package com.example.positioning.service;


import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/afterwebSocket")
public class AfterWebSocket {
    private Session session;

    private static CopyOnWriteArraySet<AfterWebSocket> afterWebSockets =new CopyOnWriteArraySet<>();

    @OnOpen
    public void opOpen(Session session){
        this.session=session;
        afterWebSockets.add(this);
        System.out.println("有新的连接,总数:"+ afterWebSockets.size());
    }
    @OnClose
    public void onClose(){
        afterWebSockets.remove(this);
        System.out.println("有连接断开,总数:"+ afterWebSockets.size());
    }
    @OnMessage
    public void onMessage(String message){
        System.out.println("收到客户端收到的消息:"+message);
    }
    public void sendMessage(String message){
        System.out.println("send");
        for(AfterWebSocket afterWebSocket : afterWebSockets){
            try {
                afterWebSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
